package com.qing.demo.netty.redis;

import cn.hutool.json.JSONString;
import cn.hutool.json.JSONUtil;
import com.qing.demo.netty.domain.UserChannelInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author caozhipeng
 * @date 2025/8/7
 */
@Service("redisUtil")
public class RedisUtil {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final String REDIS_KEY_PREFIX = "netty:";

    public void pushObj(UserChannelInfo userChannelInfo){
        stringRedisTemplate.opsForHash().put(REDIS_KEY_PREFIX,userChannelInfo.getChannelId(), JSONUtil.toJsonStr(userChannelInfo));
    }


    public List<UserChannelInfo> popList(){
        List<Object> values = stringRedisTemplate.opsForHash().values(REDIS_KEY_PREFIX);
        if(null==values) return new ArrayList<>();
        List<UserChannelInfo> userChannelInfoList=new ArrayList<>();
        for (Object value : values) {
            userChannelInfoList.add(JSONUtil.toBean(value.toString(), UserChannelInfo.class));
        }
        return userChannelInfoList;
    }

    public void remove(String channelId){
        stringRedisTemplate.opsForHash().delete(REDIS_KEY_PREFIX,channelId);
    }

    public void clear(){
        stringRedisTemplate.delete(REDIS_KEY_PREFIX);
    }


}
